package org.third.common.utils.rest;


import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.third.common.http.HttpHeader;
import org.third.common.utils.HttpUtils;
import org.third.common.utils.StringUtils;

import java.io.IOException;

public class BasicAuthHeaderHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    private String integrationUser;
    private String integrationPassword;

    public BasicAuthHeaderHttpRequestInterceptor(String integrationUser, String integrationPassword) {
        this.integrationUser = integrationUser;
        this.integrationPassword = integrationPassword;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
        if (StringUtils.hasText(integrationUser) && StringUtils.hasText(integrationPassword)) {
            requestWrapper.getHeaders().add(HttpHeader.AUTHORIZATION.getName(), HttpUtils. getBasicAuth(integrationUser, integrationPassword));
        }
        return execution.execute(requestWrapper, body);
    }}
